import { User } from '@app/db/entity/User';
import { WaterBills } from '@app/db/entity/WaterBills';
import { Injectable } from '@nestjs/common';
import { And, FindOptionsWhere, In, LessThanOrEqual, MoreThanOrEqual } from 'typeorm';
import { DbService } from '../../db/db.service';
import PageDto from './dto/page.dto';
import { WaterTest } from '@app/db/entity/WaterTest';

@Injectable()
export class WaterTestService {
    constructor(
            private readonly db:DbService,
    ){}


    async page(dto:PageDto) {
        let result:PaginationResult<WaterTest & {user? : User,}> = {
            total : 0,
            rows : []
        }

        let where:FindOptionsWhere<WaterTest> = {

        }

        if(dto.status != undefined) {
            where.status = dto.status
        }


        if(dto.deviceId && dto.deviceId > 0) {
            where.deviceId = dto.deviceId
        }


        if(dto.startTime || dto.endTime) {
            if(dto.startTime == dto.endTime) {
                where.createTime = dto.startTime
            }else {
                const dates:any = []
                if(dto.startTime) {
                    dates.push(MoreThanOrEqual(dto.startTime))
                }

                if(dto.endTime) {
                    dates.push(LessThanOrEqual(dto.endTime))
                }

                where.createTime = And(...dates)
            }
        }


        


        result.total = await this.db.waterTest.count(where)

        if(result.total > 0) {

            result.rows = await this.db.waterTest.pagination(dto.pageNo, dto.pageSize, where, {id: true, result: true, deviceId: true, userId: true, status: true, endTime:true, createTime: true, type: true}, {id : 'DESC'})

            if(result.rows.length > 0) {

                const userIds:number[] = []

                result.rows.forEach(row => {
                    if(row.userId > 0 && !userIds.includes(row.userId)) {
                        userIds.push(row.userId)
                    }
                })

                if(userIds.length > 0) {
                    const users = await this.db.user.find({id : In(userIds)}, {id : true, nickname : true, avatar : true})
                    

                    if(users.length > 0) {
                        result.rows.forEach(row => {
                            if(row.userId > 0) {
                                const user = users.find(item => item.id == row.userId)
                                if(user) {
                                    row.user = user
                                }
                            }
                        })
                    }
                }
            }
        }

        return result
    }


    async testData(id:number) {
        const r = await this.db.waterTest.findOne({id: id}, {id: true, data: true})
        return r ? r.data : null
    }
}
